﻿using System;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace FlightSearchServer
{
    public class CustomHttpBehaviorExtensionElement : BehaviorExtensionElement
    {
        protected override object CreateBehavior()
        {
            return new CustomHttpBehavior();
        }

        public override Type BehaviorType
        {
            get { return typeof (CustomHttpBehavior); }
        }
    }

    public class CustomHttpBehavior : WebHttpBehavior
    {
        protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
        {
            return new CustomQueryStringConverter();
        }
    }

    public class CustomQueryStringConverter : QueryStringConverter
    {
        public override bool CanConvert(Type type)
        {
            return type == typeof(string[]) || base.CanConvert(type);
        }

        public override object ConvertStringToValue(string parameter, Type parameterType)
        {
            if (parameterType == typeof(string[]))
            {
                return !string.IsNullOrEmpty(parameter) ? parameter.Split(',') : new string[0];
            }

            return base.ConvertStringToValue(parameter, parameterType);
        }

        public override string ConvertValueToString(object parameter, Type parameterType)
        {
            if (parameterType == typeof(string[]))
            {
                return string.Join(",", parameter as string[] ?? new string[0]);
            }

            return base.ConvertValueToString(parameter, parameterType);
        }
    }
}
